package com.mimose.cosy.proxy.api;

import com.mimose.cosy.lang.Objs;
import com.mimose.cosy.proxy.enums.ProxyType;

import javax.annotation.Nonnull;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author mimose
 * @description dynamic proxy api
 * @date 2021/4/24
 */
public abstract class DynamicProxy implements InvocationHandler, IProxy {

    private Object proxyTarget;

    public DynamicProxy() {
    }

    @Override
    public ProxyType proxyType() {
        return ProxyType.DYNAMIC;
    }

    @Override
    public Object wrap(@Nonnull Object proxyTarget) {
        Objs.requireNonNull(proxyTarget, "Dynamic Proxy fail, the target is null");
        newProxy(proxyTarget);
        this.proxyTarget = proxyTarget;

        InvocationHandler handler = newProxy(this.proxyTarget);
        return java.lang.reflect.Proxy.newProxyInstance(
                handler.getClass().getClassLoader(),
                this.proxyTarget.getClass().getInterfaces(),
                handler
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            // do before
            beforeInvoke(method, args);
            // process
            final Object result = method.invoke(proxyTarget, args);
            // do after
            afterInvoke(result, method, args);
            return result;
        } catch (Exception e) {
            // do after throw exception
            afterThrowing(e, method, args);
            throw e;
        }
    }

    public abstract DynamicProxy newProxy(@Nonnull Object proxyTarget);

}
